/*
 * This file is part of the TKPanorama library.
 *
 *  Author: Tae Kim <conrkim@gmail.com>
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of
 * the License
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

/*
 이 파일을 제공받는 사람은 이 주석을 지울 수 없습니다.
 
 TKPanorama library는 PanoramaGL library를 업그레이드한 iOS 기반의 라이브러리로서, 다음 부분에서 업그레이드가 이루어졌습니다.
 1. PanoramaGL 부분에서 #ifdef ORIGINAL_파일명_확장자명 ~ #endif 로 싸인 부분은 제외되었음.
 2. PanoramaGL 부분에서 #ifdef MODIFIED_BY_TAEKIM ~ #endif 로 싸인 부분은 새로 추가되었음.
 3. 원본은 폰을 기울이거나 화면을 터치하고 있을 때 파노라마가 움직였으나, 손가락으로 터치하여 드래그한 만큼 움직이도록 수정함.
 4. 확대/축소 후 자유롭게 움직일 수 있도록 업그레이드
 5. 약간의 상수 변경
 
 2012 Tae Kim.
 */

#import "TKPanoramaView.h"
#import "PLRenderer.h"

@interface PLView ()
- (void)allocAndInitVariables;
- (void)drawViewInternally;
- (BOOL)executeDefaultAction:(NSSet *)touches;
@end

@implementation TKPanoramaView

@synthesize imageSize;
- (void)setDelegate:(NSObject<TKPanoramaViewDelegate> *)aDelegate
{
    [super setDelegate:aDelegate];
}
- (NSObject<TKPanoramaViewDelegate> *)delegate
{
    return (NSObject<TKPanoramaViewDelegate> *)[super delegate];
}


- (void)allocAndInitVariables
{
    [super allocAndInitVariables];
    
    imageSize= CGSizeZero;
    
    tapGesture= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(detectedTap:)];
    panGesture= [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectedPan:)];
    pinchGesture= [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(detectedPinch:)];
    
    [self addGestureRecognizer:tapGesture];
    tapGesture.delegate= self;
    [self addGestureRecognizer:panGesture];
    panGesture.delegate= self;
    [self addGestureRecognizer:pinchGesture];
    pinchGesture.delegate= self;
    
    // Panorama 초기 설정
    self.isDeviceOrientationEnabled = NO;
	self.isAccelerometerEnabled = NO;
	self.isScrollingEnabled = NO;
	self.isInertiaEnabled = NO;
	self.controlTypeSupported = PLControlTypeSupportedNone;
	self.type = PLViewTypeCylindrical;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)dealloc
{
    [super dealloc];
}

- (float)getYaw
{
	if(scene && scene.currentCamera)
        return [scene.currentCamera getYaw];
    return 0;
}

- (CGFloat)getTransY
{
	if(renderer)
        return [renderer transY];
    return 0;    
}

- (CGFloat)getScale
{
	if(renderer)
        return [renderer scale];
    return 0;    
}

- (void)setYaw:(float)value
{
    [scene.currentCamera setYaw:value];
}

- (void)setScale:(CGFloat)scale
{
    [renderer setScale:scale];
}

- (void)setBackgroundImageWithPath:(NSString *)path
{
    // 실린더의 이미지를 교체한다.
	[self removeAllTextures];
    [self addTextureAndRelease:[PLTexture textureWithPath:path]];
    
    // 이미지의 사이즈를 저장해둔다. (아이템 뷰의 위치를 맞추기 위해서임)
	UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];
    imageSize= image.size;
    [image release];
    
    [renderer render];
}

- (void)cleanViewInternally
{
    [self removeAllTextures];
}

#pragma mark - Override

- (void)drawViewInternally
{
    // do nothing
//    [super drawViewInternally];
}

- (void)drawView
{
    [renderer render];
    
    // move items
    if ([self.delegate respondsToSelector:@selector(didDrawTKView:)])
    {
        [self.delegate didDrawTKView:self];
    }
}

#pragma mark - touches

- (void)detectedTap:(UITapGestureRecognizer *)gestureRecognizer
{
    if ([self.delegate respondsToSelector:@selector(detectedTap:TKView:)])
        [self.delegate detectedTap:gestureRecognizer TKView:self];
}

- (void)detectedPan:(UIPanGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged)
    {        
        CGPoint translation = [gestureRecognizer translationInView:[self superview]];
        
        scene.currentCamera.yaw+= translation.x / 3;
        [renderer setTransY:renderer.transY - translation.y];
        
        [gestureRecognizer setTranslation:CGPointZero inView:[self superview]];
        [self drawView];
    }
    
    if ([self.delegate respondsToSelector:@selector(detectedPan:TKView:)])
        [self.delegate detectedPan:gestureRecognizer TKView:self];
}

- (void)detectedPinch:(UIPinchGestureRecognizer *)gestureRecognizer
{    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged)
    {        
        CGFloat scale= renderer.scale * [gestureRecognizer scale];
        [renderer setScale:scale];
        
        [gestureRecognizer setScale:1];
        [self drawView];
    }
    
    if ([self.delegate respondsToSelector:@selector(detectedPinch:TKView:)])
        [self.delegate detectedPinch:gestureRecognizer TKView:self];
}

// 출처 - http://stackoverflow.com/questions/3344341/uibutton-inside-a-view-that-has-a-uitapgesturerecognizer
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIControl class]]) {
        // we touched a button, slider, or other UIControl
        return NO; // ignore the touch
    }
    return YES; // handle the touch
}

@end
